package fragmentson;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.wq.cycling.DemoApplication;
import com.wq.cycling.R;

import java.io.File;

import activity.ParentActivity;
import activity.SonActivity;
import bean.MessageForSimple;
import fragmentson.backhandle.BackHandledFragment;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import service.ApiUtil;
import service.AsyncTaskForUpdata;
import util.MySharePerference;
import util.dialog.DialogForLoading;
import util.dialog.DialogForUpdata;
import util.dialog.DialogFromMiddle;

/**
 * 登录
 * author：wangqi on 2017/4/26 17:48
 * email：773630555@qq.com
 */
public class LogonFragment_A extends BackHandledFragment {

	private View rootView;
	private TextView operationTextView;
	private DialogForLoading loadingDialog;
	private DialogForUpdata dialogForUpdata;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = getLayoutInflater(savedInstanceState).inflate(R.layout.fragment_logon_a, null);
		initView();
		initVersion();
		return rootView;
	}

	private void initView() {
		// TODO Auto-generated method stub
		loadingDialog = new DialogForLoading(getActivity());
		operationTextView = ((TextView) rootView.findViewById(R.id.tv_operation));
		operationTextView.setText(R.string.logon_register);
		operationTextView.setOnClickListener(listener);
		((TextView)rootView.findViewById(R.id.tv_title)).setText(R.string.logon_login);
		rootView.findViewById(R.id.tv_forget).setOnClickListener(listener);
		rootView.findViewById(R.id.tv_login).setOnClickListener(listener);
	}

	public static LogonFragment_A newInstance() {
		LogonFragment_A fragment = new LogonFragment_A();
		return fragment;
	}

	private View.OnClickListener listener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()){
				case R.id.tv_login:
					loadingDialog.show();
					ApiUtil.getApiService().login(((EditText) rootView.findViewById(R.id.et_phone)).getText().toString(), ((EditText) rootView.findViewById(R.id.et_password)).getText().toString()).enqueue(new Callback<MessageForSimple>() {
						@Override
						public void onResponse(Call<MessageForSimple> call, Response<MessageForSimple> response) {
							loadingDialog.dismiss();
							try {
								MessageForSimple entity = response.body();
								if(entity.getCode().equals("10005")){
									getActivity().finish();
									startActivity(new Intent(getActivity(), ParentActivity.class));
									MySharePerference.addSharePerference(getActivity(),"ACCOUTN",((EditText) rootView.findViewById(R.id.et_phone)).getText().toString());
								}else{
									Toast.makeText(getActivity(),entity.getMsg(),Toast.LENGTH_LONG).show();
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
						@Override
						public void onFailure(Call<MessageForSimple> call, Throwable t) {
							Toast.makeText(getActivity(),getResources().getString(R.string.error),Toast.LENGTH_LONG).show();
						}
					});

					//登录环信
					EMClient.getInstance().login("wangqi", "123456", new EMCallBack() {

						@Override
						public void onSuccess() {
							Log.d("denglu", "login: onSuccess");


							// ** manually load all local groups and conversation
							EMClient.getInstance().groupManager().loadAllGroups();
							EMClient.getInstance().chatManager().loadAllConversations();

							// update current user's display name for APNs
							boolean updatenick = EMClient.getInstance().pushManager().updatePushNickname(
									DemoApplication.currentUserNick.trim());
							if (!updatenick) {
								Log.e("LoginActivity", "update current user nick fail");
							}
							// get user's info (this should be get from App's server or 3rd party service)

						}

						@Override
						public void onProgress(int progress, String status) {
							Log.d("denglu", "login: onProgress");
						}

						@Override
						public void onError(final int code, final String message) {
							Log.d("denglu", "login: onError: " + code);
						}
					});

					break;
				case R.id.tv_operation:
					((SonActivity)getActivity()).addFragment(LogonFragment_B.newInstance("1"));
					break;
				case R.id.tv_forget:
					((SonActivity)getActivity()).addFragment(LogonFragment_B.newInstance("2"));
					break;
				default:
					break;
			}
		}
	};

	private void  initVersion(){
		ApiUtil.getApiService().getVersion("android","pre").enqueue(new Callback<MessageForSimple>() {
			@Override
			public void onResponse(Call<MessageForSimple> call, Response<MessageForSimple> response) {
				try {
					final MessageForSimple entity = response.body();
					if(entity.getCode().equals("10008")){
						DialogFromMiddle dialogFormMiddle = new DialogFromMiddle(getActivity());
						dialogFormMiddle.setSureListener(new DialogFromMiddle.Sure() {
							@Override
							public void onSure() {

								if(entity.getData().getNativeurl().isEmpty()){
									Intent it = new Intent(Intent.ACTION_VIEW);
									it.setData(Uri.parse(entity.getData().getWeburl()));
									it = Intent.createChooser(it, null);
									startActivity(it);
								}else{
									dialogForUpdata = new DialogForUpdata(getActivity());
									dialogForUpdata.show();
									AsyncTaskForUpdata task = new AsyncTaskForUpdata(new AsyncTaskForUpdata.Listener() {
										@Override
										public void finish(String path) {
											// TODO Auto-generated method stub
											dialogForUpdata.dismiss();
											Intent intent2 = new Intent();
											intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
											intent2.setAction(android.content.Intent.ACTION_VIEW);
											Uri uri = Uri.fromFile(new File(path)); // 这里是APK路径
											intent2.setDataAndType(uri,"application/vnd.android.package-archive");
											startActivity(intent2);
										}
									},getActivity());
									task.execute(entity.getData().getNativeurl(),"app-axq.apk");
									//task.execute("http://openbox.mobilem.360.cn/index/d/sid/3101204","app-zx.apk");
								}

							}
						});
						if(!entity.getData().getVersion().equals(DemoApplication.getVersion())) {
							try {
								int serviceCode = Integer.valueOf(entity.getData().getVersion().replace(".",""));
								int nowCode = Integer.valueOf(DemoApplication.getVersion().replace(".",""));
								if(nowCode<serviceCode) {
									dialogFormMiddle.show(getResources().getString(R.string.dialog_title4), getResources().getString(R.string.dialog_content4), "", "", getResources().getString(R.string.dialog_yes4),getResources().getString(R.string.dialog_no4), !entity.getData().isForceinstall());
								}
							}catch (Exception e){

							}

						}
					}else{
						Toast.makeText(getActivity(),entity.getMsg(),Toast.LENGTH_LONG).show();
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			@Override
			public void onFailure(Call<MessageForSimple> call, Throwable t) {
				Toast.makeText(getActivity(),"服务器发生错误",Toast.LENGTH_LONG).show();
			}
		});
	}

	@Override
	public boolean onBackPressed() {
		return false;
	}

	@Override
	public void onResume() {
		super.onResume();
		IntentFilter intentFilter=new IntentFilter();
		intentFilter.addAction("ACTION_UPDATE");
		getActivity().registerReceiver(broadcastReceiver, intentFilter);
	}

	@Override
	public void onPause() {
		getActivity().unregisterReceiver(broadcastReceiver);
		super.onPause();
	}

	BroadcastReceiver broadcastReceiver=new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if ("ACTION_UPDATE".equals(intent.getAction())) {
               /* try {*/
				dialogForUpdata.setProgress(intent.getIntExtra("finished", 0));
               /* }catch (Exception e){

                }*/

			}
		}
	};
	
}
